<template>
	<view>

		<map id="map" scale="13" :longitude="from.longitude" :latitude="from.latitude" :enable-poi="true" class="map"
			:style="mapStyle" :polyline="polyline" :markers="markers" @longpress="showHandle">
			<image class="location" src="/static/workbench/location.png" @tap="returnLocationHandle()" />
		</map>

		<view class="panel" v-show="infoStatus">
			<view class="info">
				<view class="label">剩余</view>
				<view class="value">{{ distance }}公里</view>
				<view class="label">，预计</view>
				<view class="value">{{ duration }}分钟</view>
				<view class="more" @tap="toOrderDetail">订单详情</view>
			</view>
			<view class="opt">
				<button class="cancel-btn" :style="cancelStyle" @tap="cancelHandle">取消订单</button>
				<button class="confirm-btn" v-if="status == 2||status == 3" @tap="driverArriviedHandle">司机到达</button>
			</view>
		</view>

	</view>
</template>

<script>
	let QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');

	import GtPush from '../../lib/gtpush-min.js'

	let qqmapsdk;
	export default {
		data() {
			return {
				mapStyle: '',
				map: null,
				orderNo: null,
				driverId: null,
				status: null,
				mode: null,
				from: {
					latitude: 0,
					longitude: 0,
				},
				to: {
					latitude: 0,
					longitude: 0,
				},
				distance: 0,
				duration: 0,
				polyline: [],
				markers: [],
				//拉取司机坐标的定时器
				driverLocationTimer: null,
				infoStatus: true,
				cancelStyle: '',
			};
		},
		methods: {
			//初始化样式
			initStyle() {
				let _this = this;
				//设置地图控件的高度适配屏幕高度
				let windowHeight = uni.getSystemInfoSync().windowHeight;
				_this.windowHeight = windowHeight;
				_this.mapStyle = `height:${_this.windowHeight}px;`;
			},
			//初始化地图
			initMap() {
				let _this = this;
				_this.map = uni.createMapContext("map");
				//初始化腾讯地图
				qqmapsdk = new QQMapWX({
					key: _this.Constants.QQMAP_KEY
				});
			},
			//加载订单的位置
			loadOrderLocation() {
				let _this = this;
				if (!_this.orderNo) return;
				console.log("---开始加载订单位置---")
				//加载订单地址
				_this.get("/order/app/order/" + _this.orderNo, (res) => {
					let {
						success,
						message,
						data
					} = res;
					if (success) {
						console.log("---加载订单位置成功---")
						console.log(data)
						_this.driverId = data.driverId;
						//根据订单状态，设置终点和驾车方式
						if (data.status == _this.Constants.OrderStatus.ORDER_STATUS_ACCEPTED) {
							console.log("---自行车---")
							//接单成功，去往订单开始位置
							_this.to.longitude = data.startPlaceLongitude;
							_this.to.latitude = data.startPlaceLatitude;
							//自行车
							_this.mode = "bicycling";
						} else if (data.status == _this.Constants.OrderStatus.ORDER_STATUS_ARRIVE ||
							data.status == _this.Constants.OrderStatus.ORDER_STATUS_START_DRIVING) {
							console.log("---驾车---")
							//开始代驾，去往订单结束位置
							_this.to.longitude = data.endPlaceLongitude;
							_this.to.latitude = data.endPlaceLatitude;
							//驾车
							_this.mode = "driving";
						} else {
							_this.closeMove();
						}
						//创建定时任务
						_this.pullDriverLocation();
						//_this.createLinePlanTimer();
					}
				});
			},
			//创建画线定时器 -- 定时去拉取司机位置
			createLinePlanTimer() {
				let _this = this;
				if (_this.timer) return;
				console.log("创建定时任务");
				_this.timer = setInterval(() => {
					_this.pullDriverLocation();
				}, 5000)
			},
			//删除画线定时器
			deleteLinePlanTimer() {
				let _this = this;
				if (_this.timer == null) return;
				clearInterval(_this.timer);
				_this.timer = null;
			},
			//拉取司机位置
			pullDriverLocation() {
				let _this = this;
				_this.get("/order/app/order/customer/schedule/driverLocation/" + _this.driverId, (res) => {
					let {
						success,
						message,
						data
					} = res;
					if (success && data) {
						_this.from.longitude = data.longitude;
						_this.from.latitude = data.latitude;
						console.log("---画线---")
						_this.remarkers();
						//划线
						_this.linePlan();
					};
				});
			},
			//标记点
			remarkers() {
				const _this = this;
				//绘制开始位置和结束位子的图标
				_this.markers = [{ //开始位置图标
						id: 1,
						latitude: _this.from.latitude,
						longitude: _this.from.longitude,
						title: "开始位置",
						iconPath: "/static/move/driver-icon.png",
						width: 32,
						height: 32
						//iconPath:"https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png"
					},
					{ //结束位置图标
						id: 2,
						latitude: _this.to.latitude,
						longitude: _this.to.longitude,
						title: "结束位置",
						iconPath: "/static/order/end.png",
						width: 25,
						height: 37
					}
				]
			},
			//路线规划
			linePlan() {
				let _this = this;
				_this.remarkers();
				qqmapsdk.direction({
					//模式：驾车
					mode: _this.mode,
					//路线规划开始位置
					from: _this.from,
					//路线规划结束位子
					to: _this.to,
					success: function(res) {
						console.log("---路线规划成功---");
						const ret = res;
						const coors = ret.result.routes[0].polyline,
							pl = [];
						//坐标解压（返回的点串坐标，通过前向差分进行压缩）
						const kr = 1000000;
						for (let i = 2; i < coors.length; i++) {
							coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
						};
						//将解压后的坐标放入点串数组pl中
						for (let i = 0; i < coors.length; i += 2) {
							pl.push({
								latitude: coors[i],
								longitude: coors[i + 1]
							})
						};
						//设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
						_this.polyline = [{
							points: pl,
							color: '#FF0000DD',
							width: 4
						}];
						_this.distance = (res.result.routes[0].distance / 1000).toFixed(2);
						_this.duration = res.result.routes[0].duration;
					},
					fail: function(error) {
						console.error(error);
					}
				});
			},
			//乘客取消订单,发送个推消息给司机
			cancelHandle() {
				const _this = this;
				const param = {
					sendId: _this.driverId,
					orderNo: _this.orderNo
				}
				_this.post("/message/app/gtPush/customer/cancelOrder", param, (res) => {
					if (res.success) {
						uni.showToast({
							title: "订单已取消",
							icon: "success"
						})
						setTimeout(() => {
							console.log("返回上一个页面")
							uni.navigateBack()
						}, 2000)
					} else {
						uni.showToast({
							title: "取消失败:" + message,
							icon: "error"
						})
					}
				});
			},
			//跳转到订单详情页面
			toOrderDetail() {
				uni.navigateTo({
					url: "../order/order?orderNo=" + _this.orderNo
				})
			},
			closeMove() {
				uni.navigateBack();
			},
		},
		onLoad: function(options) {
			let _this = this;
			_this.orderNo = options.orderNo;
			_this.initStyle();
			_this.initMap();
			uni.$on('closeMove', this.closeMove);
		},
		onShow: function() {
			let _this = this;
			//拉取订单位置
			_this.loadOrderLocation();
		},
		onHide: function() {
			let _this = this;
			_this.deleteLinePlanTimer();
		},
		onUnload() {
			let _this = this;
			_this.deleteLinePlanTimer();
			uni.$off('closeMove', this.closeMove);
		}
	};
</script>

<style lang="less">
	@import url('move.less');
</style>